<template></template>

<script setup lang="ts">
import * as L from 'leaflet'
import QyzPoint from './components/point.vue'
import { useMonitoringStore } from '@/pages/integrated-monitoring/store/store'
import apiList from '@/pages/integrated-monitoring/api/api'
const zdskjcCurrentSelect = computed(() => monitoringStore.zdskjcCurrentSelect)
const monitoringStore = useMonitoringStore()
const point = ref([])
const unitList = ref({})
const codeList = ref([])
const initData = async () => {
  console.log(monitoringStore.regional)
  if (!monitoringStore.regional) return
  const res = await apiList.getStationList({
    countyName: monitoringStore.regional,
    stationType: '1'
  })
  codeList.value = []
  for (let item of res.data) {
    codeList.value.push(item.stationCode)
  }
  const { data } = await apiList.getMultiStationWeatherFacts({
    elementCode: zdskjcCurrentSelect.value,
    stationCodes: codeList.value.join()
  })
  unitList.value = data
  point.value = res.data
  handleInitMap()
}
const baseMap = inject('baseMap')

const layer = L.layerGroup().addTo(toRaw(baseMap.value))

const handleInitMap = () => {
  point.value.forEach(item => {
    const markerContainer = document.createDocumentFragment()
    if (unitList.value && Object.keys(unitList.value).length != 0) {
      for (let key in unitList.value) {
        if (item.stationCode == key) {
          item.unit = unitList.value[item.stationCode]
          const pointDom = createApp(QyzPoint, {
            item
          }).mount(markerContainer)
          const marker = L.marker([item.latitude, item.longitude], {
            icon: L.divIcon({
              html: pointDom.$el
            })
          })
          layer.addLayer(marker)
        }
      }
    } else {
      const pointDom = createApp(QyzPoint, {
        item
      }).mount(markerContainer)
      const marker = L.marker([item.latitude, item.longitude], {
        icon: L.divIcon({
          html: pointDom.$el
        })
      })
      layer.addLayer(marker)
    }
  })
}

watch(
  () => monitoringStore.regional,
  newV => {
    layer.clearLayers()
    initData()
  },
  {
    immediate: true,
    deep: true
  }
)

onMounted(() => {
  // initData()
})

onUnmounted(() => {
  toRaw(baseMap.value).removeLayer(layer)
})
</script>

<style lang="scss"></style>
